package com.atguigu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * gateway全局过滤拦截
 * @author timiv
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {

    /**
     * 过滤拦截
     * @param exchange exchange
     * @param chain chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        log.info("*****************come in GatewayFilter:  "+ new Date());
        if(uname == null){
            log.info("*****************用户名为空，非法请求***************");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的顺序，值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
